<template>
  <div>
    <div class="top">
      <el-input
        v-model="kwInput"
        style="width: 400px"
        placeholder="输入配置名称进行筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="getList"
      >
        <el-button slot="append" icon="el-icon-search" @click="getList">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create')"
      >添加配置
      </el-button>
      <el-button
        type="info"
        class="el-icon-question add-btn"
        @click="helpDialogVisible = true"
      >如何获取凭据？
      </el-button>
    </div>

    <!-- 帮助对话框 -->
    <el-dialog
      title="如何获取 Cloudflare 凭据"
      :visible.sync="helpDialogVisible"
      width="700px"
    >
      <div style="line-height: 1.8;">
        <el-alert
          title="此配置可用于 Cloudflare Pages 部署 和 Cloudflare Images 上传"
          type="info"
          :closable="false"
          style="margin-bottom: 15px;"
        />

        <h3>推荐：使用 Global API Key（简单）</h3>
        <el-alert
          title="Global API Key 最简单，只需要邮箱和 API Key 即可"
          type="success"
          :closable="false"
          style="margin-bottom: 10px;"
        />
        <ol>
          <li>在 Cloudflare 控制台，点击右上角头像 > <strong>My Profile</strong></li>
          <li>选择左侧 <strong>"API Tokens"</strong> 标签</li>
          <li>找到 <strong>"Global API Key"</strong> 部分</li>
          <li>点击 <strong>"View"</strong> 按钮</li>
          <li>输入密码验证后，复制 Global API Key</li>
          <li>配合您的 Cloudflare 账户邮箱使用即可</li>
        </ol>

        <h3 style="margin-top: 20px;">高级：使用 API Token + Account ID</h3>
        <el-alert
          title="如果需要更细粒度的权限控制，可以使用 API Token"
          type="info"
          :closable="false"
          style="margin-bottom: 10px;"
        />

        <h4>1. 获取 Account ID</h4>
        <ol>
          <li>登录 <a href="https://dash.cloudflare.com" target="_blank">Cloudflare 控制台</a></li>
          <li><strong>方法一（推荐）：</strong>
            <ul style="margin-top: 5px;">
              <li>点击左侧菜单 "Workers & Pages"</li>
              <li>在右侧边栏的底部可以看到 "Account ID"</li>
              <li>这是一个32位的十六进制字符串（例如：a1b2c3d4e5f6...）</li>
            </ul>
          </li>
          <li><strong>方法二：</strong>
            <ul style="margin-top: 5px;">
              <li>在控制台首页，点击任意一个域名</li>
              <li>在右侧边栏的底部可以看到 "Account ID" 和 "Zone ID"</li>
              <li>复制 "Account ID"（不是 Zone ID）</li>
            </ul>
          </li>
        </ol>

        <h4 style="margin-top: 15px;">2. 创建 API Token</h4>
        <ol>
          <li>在 Cloudflare 控制台，点击右上角头像 > <strong>My Profile</strong></li>
          <li>选择左侧 <strong>"API Tokens"</strong> 标签</li>
          <li>点击 <strong>"Create Token"</strong></li>
          <li>选择 <strong>"Edit Cloudflare Workers"</strong> 模板，或者：</li>
          <li>选择 <strong>"Custom token"</strong>，手动添加权限：
            <ul style="margin-top: 5px;">
              <li>Account - <strong>Cloudflare Pages - Edit</strong> (用于部署)</li>
              <li>Account - <strong>Cloudflare Images - Edit</strong> (用于图片上传)</li>
            </ul>
          </li>
          <li>点击 "Continue to summary"</li>
          <li>点击 "Create Token"</li>
          <li><strong style="color: #F56C6C;">复制生成的 Token（注意：Token 只显示一次，请妥善保存）</strong></li>
        </ol>

        <el-divider />

        <el-alert
          title="说明：此配置可用于 Cloudflare Pages 部署和 Cloudflare Images 上传"
          type="info"
          :closable="false"
        />

      </div>
    </el-dialog>

    <el-table
      v-loading="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" width="80" prop="id" label="ID" />
      <el-table-column align="center" label="配置名称" prop="name" min-width="150" />
      <el-table-column align="center" label="认证方式" width="150">
        <template slot-scope="scope">
          <el-tag :type="scope.row.email ? 'success' : 'primary'" size="small">
            {{ scope.row.email ? 'Global API Key' : 'API Token' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="Account ID" prop="account_id" min-width="200" show-overflow-tooltip />
      <el-table-column align="center" label="邮箱" prop="email" min-width="180" show-overflow-tooltip />
      <el-table-column align="center" label="状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'info'" size="small">
            {{ scope.row.is_active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后使用" prop="last_used_at" width="160" />
      <el-table-column align="center" label="创建时间" prop="create_at" width="160" />
      <el-table-column align="center" label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="data.length"
      background
      class="mt-pagination"
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog
      append-to-body
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="600px"
    >
      <el-form :model="temp" label-position="left" label-width="150px">
        <el-form-item v-if="action !== 'delete'" label="配置名称" required>
          <el-input v-model="temp.name" placeholder="例如：生产环境、测试环境" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="认证方式">
          <el-radio-group v-model="temp.auth_type" size="small">
            <el-radio-button label="key">Global API Key（推荐）</el-radio-button>
            <el-radio-button label="token">API Token（高级）</el-radio-button>
          </el-radio-group>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            当前模式: {{ temp.auth_type }} (key=Global API Key, token=API Token)
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete' && temp.auth_type === 'key'" label="邮箱地址" required>
          <el-input v-model="temp.email" placeholder="您的 Cloudflare 账户邮箱" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete' && temp.auth_type === 'key'" label="Global API Key" required>
          <el-input v-model="temp.api_token" type="password" placeholder="在 My Profile > API Tokens 页面查看" show-password />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            在 Cloudflare 控制台，头像 > My Profile > API Tokens > Global API Key > View
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete' && temp.auth_type === 'token'" label="Account ID" required>
          <el-input v-model="temp.account_id" placeholder="在右侧边栏或 URL 中查找" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete' && temp.auth_type === 'token'" label="API Token" required>
          <el-input v-model="temp.api_token" type="password" placeholder="需要 Pages:Edit 或 Images:Edit 权限" show-password />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            可用于 Cloudflare Pages 部署和 Cloudflare Images 上传
          </div>
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="是否启用">
          <el-switch v-model="temp.is_active" />
        </el-form-item>

        <el-form-item v-if="action === 'delete'" label="确认删除">
          <el-alert
            title="删除后无法恢复，确定要删除此配置吗？"
            type="warning"
            :closable="false"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/static_web/cloudflare'

export default {
  name: 'CloudflareCfg',
  data() {
    return {
      data: [],
      total: 0,
      page: 1,
      pagesize: 20,
      kwInput: '',
      listLoading: false,
      dialogVisible: false,
      helpDialogVisible: false,
      saving: false,
      action: '',
      title: '',
      temp: {
        id: null,
        name: '',
        auth_type: 'key', // 'key' 或 'token'
        email: '', // Global API Key 需要
        account_id: '',
        api_token: '',
        is_active: true
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      const params = {
        page: this.page,
        pagesize: this.pagesize,
        kw: this.kwInput
      }

      Get(null, Object.keys(params).map(key => `${key}=${params[key]}`).join('&'))
        .then(response => {
          this.data = response.data || []
          this.total = response.total || 0
          this.listLoading = false
        }).catch(() => {
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action

      if (action === 'create') {
        this.title = '添加 Cloudflare 配置'
        // 使用 Object.assign 确保响应性
        Object.assign(this.temp, {
          id: null,
          name: '',
          auth_type: 'key',
          email: '',
          account_id: '',
          api_token: '',
          is_active: true
        })
      } else if (action === 'edit') {
        this.title = '修改 Cloudflare 配置'
        // 确保 auth_type 有值
        const authType = row.auth_type || (row.email ? 'key' : 'token')
        Object.assign(this.temp, {
          ...row,
          auth_type: authType
        })
      } else if (action === 'delete') {
        this.title = '删除 Cloudflare 配置'
        Object.assign(this.temp, row)
      }

      this.dialogVisible = true
    },
    handleSubmit() {
      // 验证必填字段
      if (this.action !== 'delete') {
        if (!this.temp.name || !this.temp.api_token) {
          this.$message.warning('请填写配置名称和API密钥')
          return
        }
        // 根据认证方式验证
        if (this.temp.auth_type === 'key') {
          if (!this.temp.email) {
            this.$message.warning('使用 Global API Key 时必须填写邮箱地址')
            return
          }
        } else {
          if (!this.temp.account_id) {
            this.$message.warning('使用 API Token 时必须填写 Account ID')
            return
          }
        }
      }

      this.saving = true

      let promise
      if (this.action === 'create') {
        promise = Post(this.temp)
      } else if (this.action === 'edit') {
        promise = Put(this.temp.id, this.temp)
      } else if (this.action === 'delete') {
        promise = Delete(this.temp.id)
      }

      promise.then(response => {
        this.saving = false
        this.$message.success(response.msg || '操作成功')
        this.dialogVisible = false
        this.getList()
      }).catch(() => {
        this.saving = false
      })
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    handlePageChange(val) {
      this.page = val
      this.getList()
    }
  }
}
</script>

<style scoped>
.top {
  margin-bottom: 20px;
}

.add-btn {
  margin-left: 10px;
}

.mt-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
